package zgrjb.snbq.teach_platform.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import zgrjb.snbq.teach_platform.dto.req.ChatRequest;
import zgrjb.snbq.teach_platform.service.ChatService;
import zgrjb.snbq.teach_platform.util.JsonData;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/api/v1/chat")
@Slf4j
public class ChatController {

    @Autowired
    private ChatService chatService;

    /**
     * 普通聊天接口
     */
    @PostMapping("/message")
    public JsonData chat(@RequestBody ChatRequest request) {
        try {
            String response = chatService.chat(request.getMessage());
            return JsonData.buildSuccess(response);
        } catch (Exception e) {
            log.error("聊天失败: {}", e.getMessage());
            return JsonData.buildError("聊天失败: " + e.getMessage());
        }
    }

    /**
     * 流式聊天接口
     */
    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(@RequestBody ChatRequest request) {
        SseEmitter emitter = new SseEmitter(30000L); // 30秒超时
        
        // 异步处理流式响应
        CompletableFuture.runAsync(() -> {
            try {
                log.info("开始流式聊天: {}", request.getMessage());
                
                // 调用AI服务进行流式对话
                chatService.streamChat(request.getMessage(), request.getFiles(), new ChatService.StreamCallback() {
                    @Override
                    public void onContent(String content) {
                        try {
                            // 发送流式数据
                            emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data("{\"content\":\"" + escapeJson(content) + "\",\"done\":false}"));
                        } catch (IOException e) {
                            log.error("发送流式数据失败: {}", e.getMessage());
                            emitter.completeWithError(e);
                        }
                    }

                    @Override
                    public void onComplete(String fullContent) {
                        try {
                            // 发送完成信号
                            emitter.send(SseEmitter.event()
                                    .name("message")
                                    .data("{\"content\":\"\",\"done\":true}"));
                            emitter.complete();
                            log.info("流式聊天完成");
                        } catch (IOException e) {
                            log.error("发送完成信号失败: {}", e.getMessage());
                            emitter.completeWithError(e);
                        }
                    }

                    @Override
                    public void onError(Exception error) {
                        log.error("流式聊天出错: {}", error.getMessage());
                        try {
                            emitter.send(SseEmitter.event()
                                    .name("error")
                                    .data("{\"error\":\"" + escapeJson(error.getMessage()) + "\"}"));
                        } catch (IOException e) {
                            log.error("发送错误信息失败: {}", e.getMessage());
                        }
                        emitter.completeWithError(error);
                    }
                });
                
            } catch (Exception e) {
                log.error("流式聊天异常: {}", e.getMessage());
                emitter.completeWithError(e);
            }
        });
        
        // 设置超时和完成回调
        emitter.onTimeout(() -> {
            log.warn("流式聊天超时");
            emitter.complete();
        });
        
        emitter.onCompletion(() -> {
            log.info("流式聊天会话结束");
        });
        
        emitter.onError((ex) -> {
            log.error("流式聊天出现错误: {}", ex.getMessage());
        });
        
        return emitter;
    }

    /**
     * AI生成试题
     */
    @PostMapping("/generate-questions")
    public JsonData generateQuestions(@RequestBody ChatRequest request) {
        try {
            String questions = chatService.generateQuestions(request.getPrompt());
            return JsonData.buildSuccess(questions);
        } catch (Exception e) {
            log.error("生成试题失败: {}", e.getMessage());
            return JsonData.buildError("生成试题失败: " + e.getMessage());
        }
    }

    /**
     * AI分析数据
     */
    @PostMapping("/analyze")
    public JsonData analyze(@RequestBody ChatRequest request) {
        try {
            String analysis = chatService.analyzeData(request.getData());
            return JsonData.buildSuccess(analysis);
        } catch (Exception e) {
            log.error("数据分析失败: {}", e.getMessage());
            return JsonData.buildError("数据分析失败: " + e.getMessage());
        }
    }

    /**
     * 转义JSON字符串
     */
    private String escapeJson(String text) {
        if (text == null) {
            return "";
        }
        return text.replace("\\", "\\\\")
                   .replace("\"", "\\\"")
                   .replace("\n", "\\n")
                   .replace("\r", "\\r")
                   .replace("\t", "\\t");
    }
} 